<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col :span="4">
                <el-select v-model="selectedType" placeholder="选择等权限级" @change="handleFilterChange"
                    class="filter-select">
                    <el-option label="所有级别" value=""></el-option>
                    <el-option label="超级管理员" value="0"></el-option>
                    <el-option label="中级管理员" value="1"></el-option>
                    <el-option label="普通管理员" value="2"></el-option>
                </el-select>
            </el-col>
            <el-col id="btn0" :span="3">
                <el-button type="primary" @click="dialogVisible = true">添加管理员信息</el-button>
            </el-col>
            <el-col :offset="11" :span="4">
                <el-input v-model="searchName" placeholder="请输入管理员ID" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedUsers" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
                @sort-change="handleSortChange">
                <el-table-column property='adminId' label="管理员ID" />
                <el-table-column property="adminPhone" label="管理员手机号" />
                <el-table-column property="adminPwd" label="管理员密码" />
                <el-table-column property="lastLogtime" label="上次登录时间" sortable="custom" />
                <el-table-column property="authorityLevel" label="权限">
                    <template #default="scope">
                        <span>{{ getLevelText(scope.row.authorityLevel) }}</span>
                    </template>
                </el-table-column>
                <el-table-column property="state" label="管理员状态">
                    <template #default="scope">
                        <span class="status-container">
                            <el-icon size="20">
                                <CircleCheck :class="getStatusIconClass(scope.row.state)" />
                            </el-icon>
                            <span>{{ getStatusText(scope.row.state) }}</span>
                        </span>
                    </template>
                </el-table-column>
                <!-- 操作按钮 -->
                <el-table-column width="250" label="操作">
                    <template #default="{ row }">
                        <!-- 删除 -->
                        <el-button type="danger" @click="handleDeleteApplication(row)" :disabled="row.state !== 1" link>
                            删除
                        </el-button>
                        <!-- 禁用 -->
                        <el-button type="warning" @click="handleAbandonQualification(row)" :disabled="row.state !== 0"
                            link>
                            禁用
                        </el-button>
                        <!-- 激活 -->
                        <el-button type="success" @click="handleApproveApplication(row)" :disabled="row.state !== 1"
                            link>
                            激活
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="旅行社表单" width="500" :before-close="handleClose">
        <template #footer>
            <div class="dialog-footer">
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                    class="demo-ruleForm" :size="formSize" status-icon>
                    <el-form-item label="管理员手机号" prop="adminPhone">
                        <el-input v-model="ruleForm.adminPhone" />
                    </el-form-item>
                    <el-form-item label="管理员密码" prop="adminPwd">
                        <el-input v-model="ruleForm.adminPwd" />
                    </el-form-item>
                    <el-form-item label="管理员级别" prop="authorityLevel">
                        <el-select v-model="ruleForm.authorityLevel" placeholder="选择权限级别">
                            <el-option label="中级管理员" value="1" />
                            <el-option label="低级管理员" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="验证状态" prop="state">
                        <el-select v-model="ruleForm.state" placeholder="选择状态">
                            <el-option label="已激活" value="0" />
                            <el-option label="待审核" value="1" />
                            <el-option label="已禁用" value="2" />
                        </el-select>
                    </el-form-item>
                    <div style="display: flex; justify-content: flex-end;">
                        <el-form-item>
                            <el-button type="primary" @click="handleSubmit">提交</el-button>
                            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                        </el-form-item>
                    </div>

                </el-form>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed, reactive } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';


// 定义接口类型
interface RuleForm {
    adminPhone: string;
    adminPwd: string;
    authorityLevel: string;
    state: number;
}

// 响应式数据
const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    adminPhone: '',
    adminPwd: '',
    authorityLevel: '',
    state: 0,
});

// 表单校验规则
const rules = reactive<FormRules<RuleForm>>({
    adminPhone: [{ required: true, message: '请输入管理员手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位的手机号', trigger: 'blur' },
    ],
    adminPwd: [{ required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, max: 16, message: '请输入长度在6-16之间的密码', trigger: 'blur' },
    ],
    authorityLevel: [{ required: true, message: '请输入管理员级别', trigger: 'change' }],
    state: [
        { required: true, message: '请选择管理员账号状态', trigger: 'change' },
    ],
});

// 显示模态框
const dialogVisible = ref(false);
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭弹窗吗?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}

// 提交表单
const handleSubmit = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const response = await axios.post('http://localhost:8088/administrators/add', ruleForm);
                console.log('提交成功:', response.data);
                getData();
                ElMessage({ message: '添加成功', type: 'success' });
                dialogVisible.value = false;
            } catch (error) {
                console.error('提交失败:', error);
                ElMessage({ message: '提交失败,请输入正确的userid', type: 'error' });
            }
        } else {
            console.log('表单校验失败!');
        }
    });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};


// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);

// 定义选中的下拉框值
const selectedType = ref('');
// 获取数据的函数
const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/administrators/filter', {
            params: {
                authorityLevel: selectedType.value,
            },
        });
        tableData.value = response.data.administrators;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

// 处理下拉框变化的函数
const handleFilterChange = () => {
    fetchData();
};

const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/administrators/getByPage', {
            params: {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
            },
        });
        tableData.value = response.data.records;
        total.value = response.data.total;
        pageNum.value = response.data.current;
        pageSize.value = response.data.size;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/administrators/getByName', { params: { adminId: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateAdministratorsStatus = async (adminId, state) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            adminId,
            state,
        };

        const response = await axios.put(
            "http://localhost:8088/administrators/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("更新成功"); // 操作成功，给用户反馈
            // 同步更新表格s中的数据状态
            const administrators = tableData.value.find((item) => item.adminId === adminId);
            if (administrators) {
                administrators.state = state;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
        return null;
    }
};

// 删除
const handleDeleteApplication = (row) => {
    updateAdministratorsStatus(row.adminId, '禁用');
    getData();
};

// 禁用
const handleAbandonQualification = (row) => {
    updateAdministratorsStatus(row.adminId, '1');
    getData();
};

// 解封
const handleApproveApplication = (row) => {
    updateAdministratorsStatus(row.adminId, '0');
    getData();
};

// 组件挂载后获取初始数据
onMounted(() => {
    fetchData();
    getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedUsers = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'lastLogtime') {
            const timeA = new Date(a.lastLogtime).getTime();
            const timeB = new Date(b.lastLogtime).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
};
//处理状态栏样式
function getStatusIconClass(state) {
    switch (state) {
        case 0:
            return 'status-icon-green';
        case 1:
            return 'status-icon-red';
        case 2:
            return 'status-icon-gray';
    }
}
function getStatusText(state) {
    switch (state) {
        case 0:
            return '激活';
        case 1:
            return '待审核';
        case 2:
            return '禁用';
    }
}

function getLevelText(authorityLevel) {
    switch (authorityLevel) {
        case '0':
            return '超级管理员';
        case '1':
            return '中级管理员';
        case '2':
            return '低级管理员';
    }
}
const handleEdit = (row) => {
    // 编辑操作的逻辑
    console.log('Editing row:', row);
};
const handleDelete = (row) => {
    // 删除操作的逻辑
    console.log('Deleting row:', row);
};
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}



.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
    color: green;
    margin-right: 5px;
    /* 图标和文本之间的间距 */
}

.status-icon-red {
    color: red;
    margin-right: 5px;
}

.status-icon-gray {
    margin-right: 5px;
    color: gray;
}
</style>